﻿#region License
// (c) Intergen.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using TextGlow.Control.Utilities;

namespace TextGlow.Control.Model
{
  public class Image : RunContent
  {
    public const string DrawingMLLocalName = "drawing";
    public const string VmlLocalName = "pict";

    private Unit _width;
    private Unit _height;
    private string _imageId;

    public Uri ImageUri
    {
      get { return GetResolvedTarget(_imageId); }
    }

    public string ImageId
    {
      get { return _imageId; }
      set { _imageId = value; }
    }

    public Unit Width
    {
      get { return _width; }
      set { _width = value; }
    }

    public Unit Height
    {
      get { return _height; }
      set { _height = value; }
    }

    public override RunContentType ContentType
    {
      get { return RunContentType.Image; }
    }

    public Image(Run parent, XElement element)
      : base(parent, element)
    {
      XNamespace ns = Document.WordprocessingDrawingML;

      XElement inlineElement = element.Element(ns + "inline");
      if (inlineElement == null)
        throw new Exception("Only inline images are supported.");

      _width = Unit.Emu(XmlUtils.GetValue<double>(inlineElement.Element(ns + "extent"), XName.Get("cx"))).Value;
      _height = Unit.Emu(XmlUtils.GetValue<double>(inlineElement.Element(ns + "extent"), XName.Get("cy"))).Value;

      XElement graphicElement = inlineElement.Element(Document.DrawingML + "graphic");
      XElement graphicDataElement = graphicElement.Element(Document.DrawingML + "graphicData");
      XElement picElement = graphicDataElement.Element(Document.PictureDrawingML + "pic");

      XElement fillElement = picElement.Element(Document.PictureDrawingML + "blipFill");

      _imageId = XmlUtils.GetValue(fillElement.Element(Document.DrawingML + "blip"), Document.Relationship + "embed");
    }

    public override string ToString()
    {
      return "{{Image: {0}}}".Format(ImageUri);
    }
  }
}